package com.jl.magic.montage.slicer;

import com.jl.magic.extract.ColorExtract;
import com.jl.magic.montage.config.AbstractInlayConfig;
import com.jl.magic.montage.config.SquareInlayConfig;
import com.jl.magic.montage.model.SubImage;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jiangli
 * @create 2020/7/14 12:41 下午
 */
public class SquareSlicer extends AbstractSlicer {

    public int[] slice;

    public SquareSlicer(BufferedImage source, AbstractInlayConfig shapeConfig, int inlayCount) {
        super(source, shapeConfig, inlayCount);
    }

    @Override
    List<SubImage> doDivide() {
        SquareInlayConfig config = (SquareInlayConfig) this.inlayConfig;
        slice = getSliceCount();
        config.setSlice(slice);

        return slice();
    }

    private List<SubImage> slice() {
        List<SubImage> result = new ArrayList<>();

        int perW = width / slice[0];
        int perH = height / slice[1];

        int[] pixels;
        byte[] pixelArr;

        for (int i = 0; i < slice[1]; i++) {
            int yStart = i * perH;
            for (int j = 0; j < slice[0]; j++) {
                int xStart = j * perW;
                BufferedImage image = new BufferedImage(perW, perH, type);
                switch (type) {
                    case BufferedImage.TYPE_3BYTE_BGR:
                    case BufferedImage.TYPE_4BYTE_ABGR:
                        pixelArr = (byte[]) source.getRaster().getDataElements(xStart, yStart, perW, perH, null);
                        image.getRaster().setDataElements(0, 0, perW, perH, pixelArr);
                        break;
                    default:
                        pixels = source.getRGB(xStart, yStart, perW, perH, null, 0, perH);
                        image.setRGB(xStart, yStart, perW, perH, pixels, 0, perH);
                }
                int[] themeColor = ColorExtract.getThemeColor(image);
                SubImage subImage = new SubImage();
                subImage.setX(j + 1);
                subImage.setY(i + 1);
                subImage.setRgb(themeColor);
                result.add(subImage);
            }
        }
        return result;
    }

    /**
     * 计算将源图分割出最少sliceCount个子图时，图片宽高等分个数
     *
     * @return Slice
     */
    private int[] getSliceCount() {

        int shortSide = Math.min(width, height);
        int longSide = shortSide == width ? height : width;

        int side = shortSide;
        int multiple = longSide / side;
        int i = 1;
        while (multiple * i < sliceCount) {
            i++;
            side = shortSide / i;
            multiple = longSide / side;
        }

        if (shortSide == width) {
            return new int[]{i, multiple};
        } else {
            return new int[]{multiple, i};
        }
    }

}
